#include "ProcessDelegate.h"
#include <QTimerEvent>
#include <QProcess>
#include <QWindow>
#include <windows.h>
#include <iostream>
#include <QVBoxLayout>
#include <QLabel>

#include "util/FileUtil.h"

#define TIMER_TIMEOUT   (1*1000)

ProcessDelegate::ProcessDelegate()
{

}



ProcessDelegate::ProcessDelegate(
    QObject *parent):
    QObject(parent)
{
    m_nTimerID = this->startTimer(TIMER_TIMEOUT);
}



ProcessDelegate::ProcessDelegate(
    QMdiArea* mdi,
    QObject* parent):
    QObject(parent)
{
    d_mdi = mdi;
    m_nTimerID = this->startTimer(TIMER_TIMEOUT);
}



ProcessDelegate::~ProcessDelegate()
{

}



void
ProcessDelegate::timerEvent(
    QTimerEvent *event)
{

#define PATCH_BYTES		200000
    DWORD PATCH_POSITION  = 0x7C92101D;


     PROCESS_INFORMATION procInfo = {0};
     STARTUPINFO startupInfo = {0};
     //startupInfo.cb = sizeof(startupInfo);
     //startupInfo.dwFlags = STARTF_USESTDHANDLES;
    // startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
     //startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    // startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
     GetStartupInfo (&startupInfo);
     HWND hWnd = (HWND)FindWindow(NULL,L"地下城与勇士");
     std::cout << "hwnd =" << hWnd << std::endl;
     DWORD PID;
     GetWindowThreadProcessId(hWnd,&PID);
     std::cout << "pid =" << PID << std::endl;
     HANDLE proc = OpenProcess (PROCESS_VM_READ,FALSE,DWORD(PID));
     std::cout << "proc =" << proc << std::endl;
     if (proc)
     {

         byte* oldBytes=new byte[256*16*1000];
         ReadProcessMemory (proc,(LPCVOID)PATCH_POSITION,oldBytes,PATCH_BYTES ,0);
         std::cout << "oldBytes = " << *oldBytes << std::endl;
         FileUtil::input_file ((char*)oldBytes,PATCH_BYTES);
     }
     else
     {
         std::cout << "proc wei null" << std::endl;
     }

     if(event->timerId() == m_nTimerID)
     {
         handleTimeout();
     }
}



void
ProcessDelegate::handleTimeout()
{
    //qDebug()<<"Enter timeout processing function\n";
    killTimer(m_nTimerID);
}

